package org.niu.twopointer;

import java.util.ArrayList;
import java.util.Arrays;

public class ThreePointer {
    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
        Arrays.sort(num);
        if(num.length < 3) return ans;
        for (int i = 0; i < num.length-2; i++) {
            if(i!=0&&num[i] == num[i-1]) continue;
            int j = i+1;
            int k = num.length-1;
            while (j < k){

                if (num[i]+num[j]+num[k]==0){
                    ArrayList<Integer> t = new ArrayList<>();
                    t.add(num[i]);
                    t.add(num[j]);
                    t.add(num[k]);
                    ans.add(t);
                }
                while (num[j]==num[j+1]) j++;
                while (num[k]==num[k-1]) k--;
                j++;
                k--;
            }
        }
        return ans;
    }
}
